package com.sgzn.sgpay.util;

import org.apache.commons.lang3.StringUtils;

/**
 * User: Terence
 * Date: 2014/5/22
 * Time: 12:43
 */
public class EnumUtil {
//    public static final <T extends Enum<T>> T resolve(Class<T> enumClass, String name) {
//        return Enums.getIfPresent(enumClass, name).get();
//    }

    /**
     * 从指定的枚举类中根据property搜寻匹配指定值的枚举实例
     *
     * @param <T>
     * @param enumClass
     * @param property
     * @param propValue
     * @return 对应枚举对象
     */
    public static <T extends Enum<T>> T fromEnumValue(Class<T> enumClass, String property, String propValue) {
        T[] enumConstants = enumClass.getEnumConstants();
        String methodName = "get" + StringUtils.capitalize(property);
        for (T t : enumConstants) {
            Object constantPropValue;
            try {
                constantPropValue = t.getDeclaringClass().getDeclaredMethod(methodName).invoke(t);
                if (constantPropValue.equals(propValue)) {
                    return t;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
//        throw new EnumConstantNotPresentException(enumClass, propValue);
        return  null;
    }

    /**
     * 通过枚举对象获取指定属性的值
     *
     * @param enumObject 枚举对象
     * @param property 枚举对象中的属性
     * @return 属性对应值
     */
    public static String getEnumProperty(Enum enumObject, String property) {
        String methodName = "get" + StringUtils.capitalize(property);
        Object constantPropValue;
        try {
            constantPropValue = enumObject.getDeclaringClass().getDeclaredMethod(methodName).invoke(enumObject);
        } catch (Exception e) {
            throw new RuntimeException(
                    String.format("could not found settable filed [%s] in [%s]", property, enumObject.getDeclaringClass())
                    , e);
        }

        return constantPropValue.toString();
    }

    /**
     * 通过枚举对象获取枚举描述值（desc)
     *
     * @param enumObject 枚举对象
     * @return 枚举描述值
     */
    public static String getEnumDesc(Enum enumObject) {
        return getEnumProperty(enumObject, "desc");
    }

    public static <T extends Enum<T>> T resolveFromCode(String code, Class<T> clazz) {
        return EnumUtil.fromEnumValue(clazz, "code", code.trim());
    }

}
